package org.angelica.common.aop;

import org.angelica.core.annotation.RequirePermission;
import org.angelica.core.common.Constant;
import org.angelica.exception.ServiceErrorEnum;
import org.angelica.exception.ServiceException;
import org.angelica.modules.account.service.AccUserService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 权限控制
 * @author aiken
 */
@Aspect
@Component
@Order(2)
public class PermissionAspect {

	@Autowired
	private AccUserService accUserService;

	@Pointcut("@annotation(requirePermission)")
	public  void annotationPointCut(RequirePermission requirePermission) {

	}

	@Before("annotationPointCut(requirePermission)")
	public void doBefore(JoinPoint joinPoint,RequirePermission requirePermission) {
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();

		//方法需要的权限字符串
		String perm = requirePermission.value();

		//查询用户拥有的权限集合
		Long currentUserId = (Long)request.getAttribute(Constant.CURRENT_USER_ID);
		List<String> permissions = accUserService.listMyPermission(currentUserId);
		if(!permissions.contains(perm)){
			throw new ServiceException(ServiceErrorEnum.NO_AUTHORITY);
		}
	}
}
